﻿--declare all values
local copper_there;
local silver_there;
local gold_there;
local copper;
local silver;
local gold;
local amountincopper;
local titheamountincopper;
local convertedtithe;
local convertedtithe2;
local convertedtithe3;
local convertedtithe4;
local guildMOTD;
local settitheamount;
local guildINFO;
local settitheamount2
local inGuild;
local numPartyMembers;
local numRaidMembers;
local unit;
local openvendoramount;
local closevendoramount;
local lastvendortithetime;
local openmailamount;
local closemailamount;
local lastmailtithetime;
local openbankamount;
local prefix = "GuildTithe: ";

function GuildTitheFrame_OnLoad()
	GuildTitheFrame:RegisterEvent("CHAT_MSG_MONEY");
	GuildTitheFrame:RegisterEvent("ADDON_LOADED");
	GuildTitheFrame:RegisterEvent("GUILDBANKFRAME_OPENED");
	GuildTitheFrame:RegisterEvent("CHAT_MSG_SYSTEM");
	GuildTitheFrame:RegisterEvent("PARTY_MEMBERS_CHANGED");
	GuildTitheFrame:RegisterEvent("RAID_ROSTER_UPDATE");
	GuildTitheFrame:RegisterEvent("MAIL_CLOSED");
	GuildTitheFrame:RegisterEvent("MAIL_SHOW");
	GuildTitheFrame:RegisterEvent("MERCHANT_CLOSED");
	GuildTitheFrame:RegisterEvent("MERCHANT_SHOW");
	
	SLASH_GUILDTITHE1 = "/tithe"
	SlashCmdList["GUILDTITHE"] = function(msg)
		GuildTithe_SlashCmdHandler(msg)
	end
end

function GuildTithe_SlashCmdHandler(msg)
	--on recieving a slash command display required selection
	ConvertToRealMoney();
	if (msg == "options") then
		GuildTitheOptionsFrame:Show();
		open_options = 1;
	elseif (msg == "show") then
		GuildTitheFrame:Show();
		open_miniframe = 1;
	elseif (msg == "total") then
		DEFAULT_CHAT_FRAME:AddMessage(prefix .."Total Tithe ever paid " .. convertedtithe4);
	elseif (msg == "tithe") then
		DEFAULT_CHAT_FRAME:AddMessage(prefix .."Tithe Pending " .. convertedtithe);
	else
		-- if unknown, or no options display instructions
		DEFAULT_CHAT_FRAME:AddMessage("**************Guild Tithe**************");
		DEFAULT_CHAT_FRAME:AddMessage("Type '/tithe show' to see the Mini Tithe Window");
		DEFAULT_CHAT_FRAME:AddMessage("Type '/tithe options' to see the Options Window");
		DEFAULT_CHAT_FRAME:AddMessage("Type '/tithe tithe' to see how much tithe will be paid next bank visit");
		DEFAULT_CHAT_FRAME:AddMessage("Type '/tithe total' to see the Total Tithe ever Paid");
	end
end

function MiniClose_OnClick()
	--on closing the Mini frame save the options
	GuildTitheFrame:Hide();
	open_miniframe = 0;
	SaveOptions();
end

function OptionsClose_OnClick()
	--on closing the options frame save the options
	GuildTitheOptionsFrame:Hide();
	open_options = 0;
	SaveOptions();
end

function GuildTitheFrame_OnEvent()
	-- Sets addon up when it first loads
	if (event == "ADDON_LOADED" and arg1 == "GuildTithe") then
		LoadOptions();
	end

	--CHAT_MSG_MONEY is the text saying when you, or your party/raid loot money.
	if (event == "CHAT_MSG_MONEY") then
		if(option_SCselfenable == 1) then
		--Collect tithe as self enabled
		CollectSmallChangeTithe(arg1);
		end	
	end
	--CHAT_MSG_SYSTEM outputs loot message when completed quest
	if (event == "CHAT_MSG_SYSTEM") then
		if(option_QRselfenable == 1) then
		--Collect tithe as self enabled
		CollectQuestRewardTithe(arg1);
		end		
	end
	
	-- Deposit tithe in guild bank when visited
	if (event == "GUILDBANKFRAME_OPENED") then
		DepositMoneyInGuild();
	end
	
	--MERCHANT_SHOW is when you open the vendors
	if (event == "MERCHANT_SHOW") then
		openvendoramount = GetMoney();
	end
	--MERCHANT_CLOSE is when you close the vendor
	if (event == "MERCHANT_CLOSED") then
		if(option_VEselfenable == 1) then
		--Collect tithe
		CollectVendorTithe("Closed");
		end
	end
	
	--MAIL_SHOW is when you open the mailbox
	if (event == "MAIL_SHOW") then
		openmailamount = GetMoney();
	end
	--MAIL_CLOSE is when you close the mail box
	if (event == "MAIL_CLOSED") then
		if(option_MBselfenable == 1) then
		--Collect tithe
		CollectMailBoxTithe("Closed");
		end
	end
end

function CollectSmallChangeTithe(arg1)
	--Collect tithe from small change
	--Check message for gold, silver and copper, if none set to 0.
	copper_there = arg1:match("%d+ Copper") or "0 Copper";
	silver_there = arg1:match("%d+ Silver") or "0 Silver";
	gold_there = arg1:match("%d+ Gold") or "0 Gold";

	--Get amounts for gold, silver and copper, if none set to 0.
	copper = (copper_there:match("%d+")) or 0
	silver = (silver_there:match("%d+")) or 0
	gold = (gold_there:match("%d+")) or 0	

	-- Calculate tithe amount in copper.
	amountincopper = copper + (silver*100) + (gold*10000);
	titheamountincopper = math.floor(((amountincopper/100)*option_SmallChangeTithePercentage));

	--Add latest tithe amount to totals.
	titheincopper_total = titheincopper_total + titheamountincopper;

	--Convert all money
	ConvertToRealMoney();

	--Output message to the frame and chat if wanted.
	MiniAmount:SetText("Tithe - " .. convertedtithe2);
	OutPutTitheMessage("Small Change", option_SmallChangeTithePercentage);
end

function CollectQuestRewardTithe(arg1)
	-- Collect tithe from quest reward
	--Check message for gold, silver and copper, if none set to 0.
	copper_there = arg1:match("%d+ Copper") or "0 Copper";
	silver_there = arg1:match("%d+ Silver") or "0 Silver";
	gold_there = arg1:match("%d+ Gold") or "0 Gold";
	
	--Get amounts for gold, silver and copper, if none set to 0.
	copper = (copper_there:match("%d+")) or 0
	silver = (silver_there:match("%d+")) or 0
	gold = (gold_there:match("%d+")) or 0
	
	--Make sure message had money in it, otherwise dont try taking tithe.
	if(copper_there == "0 Copper" and silver_there == "0 Silver" and gold_there == "0 Gold") then
		-- do nothing, as no money
	else
		-- Calculate tithe amount in copper.
		amountincopper = copper + (silver*100) + (gold*10000);
		titheamountincopper = math.floor(((amountincopper/100)*option_QuestRewardsTithePercentage));
		
		--Add latest tithe amount to totals.
		titheincopper_total = titheincopper_total + titheamountincopper;
			
		--Convert all money
		ConvertToRealMoney();
		
		--Output message to the frame and chat if wanted.
		MiniAmount:SetText("Tithe - " .. convertedtithe2);
		OutPutTitheMessage("Quest Rewards", option_QuestRewardsTithePercentage);
	end
end

function CollectVendorTithe(arg1)
	-- Collect tithe from the vendor
	if (arg1 == "Closed") then
		if(lastvendortithetime == nil) then
			lastvendortithetime = 0;
		end
		lastvendortithetime = GetTime() - lastvendortithetime;
		if(lastvendortithetime < 2) then
			-- dont do anything, as means the vendor is tryin to run twice
		else
			--get the amount of money the player has on closing the vendor window
			closevendoramount = GetMoney();
			--compare the amounts, see if player has made money.
			closevendoramount = closevendoramount - openvendoramount;
			if(closevendoramount < 0) then
				closevendoramount = 0;
			end
			--tithe any money made
			titheamountincopper = math.floor(((closevendoramount/100)*option_VendorTithePercentage));
			titheincopper_total = titheincopper_total + titheamountincopper;
			--Convert all money
			ConvertToRealMoney();
			--Output message to the frame and chat if wanted.
			MiniAmount:SetText("Tithe - " .. convertedtithe2);
			OutPutTitheMessage("the Vendor", option_VendorTithePercentage);
			lastvendortithetime = GetTime();
		end
	end
end

function CollectMailBoxTithe(arg1)
	-- Collect tithe from the mail box
	if (arg1 == "Closed") then
		if(lastmailtithetime == nil) then
			lastmailtithetime = 0;
		end
		lastmailtithetime = GetTime() - lastmailtithetime;
		if(lastmailtithetime < 2) then
			-- dont do anything, as means the mail box is tryin to run twice
		else
			--get the amount of money the player has on closing the mailbox
			closemailamount = GetMoney();
			--compare the amounts, see if player has made money.
			closemailamount = closemailamount - openmailamount;
			if(closemailamount < 0) then
				closemailamount = 0;
			end
			--tithe any money made
			titheamountincopper = math.floor(((closemailamount/100)*option_MailBoxTithePercentage));
			titheincopper_total = titheincopper_total + titheamountincopper;
			--Convert all money
			ConvertToRealMoney();
			--Output message to the frame and chat if wanted.
			MiniAmount:SetText("Tithe - " .. convertedtithe2);
			OutPutTitheMessage("the Mail Box", option_MailBoxTithePercentage);
			lastmailtithetime = GetTime();
		end
	end
end

function DepositMoneyInGuild()
	-- Deposit tithe in guild bank when visited
	if(option_bankdepositsenable == 1) then --only add to bank if allowed by user option
		--Convert all money
		ConvertToRealMoney();
		openbankamount = GetMoney();
		if(openbankamount > titheincopper_total)then
			--Deposit Tithe in bank
			DepositGuildBankMoney(titheincopper_total);
			--Update toal ever amount paid
			totalevertitheed_amount = totalevertitheed_amount + titheincopper_total;
			--Output message sayin how much banked
			DEFAULT_CHAT_FRAME:AddMessage(prefix .. convertedtithe .. " Deposited");

			--Reset Tithe amount
			titheincopper_total = 0;
			
			--Display new tithe amount (should be 0 as just been reset)
			ConvertToRealMoney();
			MiniAmount:SetText("Tithe - " .. convertedtithe2);
		end
	else
		-- Bank Deposits Disabled
		DEFAULT_CHAT_FRAME:AddMessage(prefix .. "Bank Deposits Disabled");
	end
end

function ConvertToRealMoney()
	--Convert to real amounts in gold, silver and copper before displaying
	convertedtithe = GetCoinText(titheincopper_total, " "); --Text string without icons
	convertedtithe2 = GetCoinTextureString(titheincopper_total, " "); --Text string with icons
	convertedtithe4 = GetCoinText(totalevertitheed_amount, " "); --Text string without icons
	if(convertedtithe == "") then
		convertedtithe = 0;
	end
	if(convertedtithe2 == "") then
		convertedtithe2 = 0;
	end
	if(convertedtithe4 == "") then
		convertedtithe4 = 0;
	end
end

function LoadOptions()
	-- Check for saved variables, set to default if none found.
	if (titheincopper_total == nil) then
		titheincopper_total = 0;
	end

	if (totalevertitheed_amount == nil) then
		totalevertitheed_amount = 0;
	end
	if (inGuild == nil) then
		inGuild = 0;
	end
	--Load options from last session, if none, set to default.
	
	if (option_SmallChangeTithePercentage == nil) then
	    option_SmallChangeTithePercentage = 5
	end
	
	SmallChange_TithePercentage:SetValue(option_SmallChangeTithePercentage)
	SmallChange_TithePercentageLabel:SetText(option_SmallChangeTithePercentage.."%")
	
	if (option_QuestRewardsTithePercentage == nil) then
	    option_QuestRewardsTithePercentage = 5
	end
	
	QuestRewards_TithePercentage:SetValue(option_QuestRewardsTithePercentage)
	QuestRewards_TithePercentageLabel:SetText(option_QuestRewardsTithePercentage.."%")

    if (option_VendorTithePercentage == nil) then
	    option_VendorTithePercentage = 5
	end
	
	Vendor_TithePercentage:SetValue(option_VendorTithePercentage)
	Vendor_TithePercentageLabel:SetText(option_VendorTithePercentage.."%")
	
	if (option_MailBoxTithePercentage == nil) then
	    option_MailBoxTithePercentage = 5
	end
	
	MailBox_TithePercentage:SetValue(option_MailBoxTithePercentage)
	MailBox_TithePercentageLabel:SetText(option_MailBoxTithePercentage.."%")

    --Small change tithe self option
	if (option_SCselfenable == nil or option_SCselfenable == 0) then
		option_SCselfenable = 0;
		option_SCself:SetChecked(false);
	else 
		option_SCselfenable = 1;
		option_SCself:SetChecked(true);
	end

	--Quest Reward tithe self option
	if (option_QRselfenable == nil or option_QRselfenable == 0) then
		option_QRselfenable = 0;
		option_QRself:SetChecked(false);
	else 
		option_QRselfenable = 1;
		option_QRself:SetChecked(true);
	end

	--Vendor tithe self option
	if (option_VEselfenable == nil or option_VEselfenable == 0) then
		option_VEselfenable = 0;
		option_VEself:SetChecked(false);
	else 
		option_VEselfenable = 1;
		option_VEself:SetChecked(true);
	end

	--Mailbox tithe self option
	if (option_MBselfenable == nil or option_MBselfenable == 0) then
		option_MBselfenable = 0;
		option_MBself:SetChecked(false);
	else 
		option_MBselfenable = 1;
		option_MBself:SetChecked(true);
	end

	--Spam chat option
	if (option_spamchatenable == nil or option_spamchatenable == 1) then
		option_spamchatenable = 1;
		option_spamchat:SetChecked(true);
	else 
		option_spamchatenable = 0;
		option_spamchat:SetChecked(false);
	end
	--Bank Deposit option
	if (option_bankdepositsenable == nil or option_bankdepositsenable == 1) then
		option_bankdepositsenable = 1;
		option_bankdeposits:SetChecked(true);
	else 
		option_bankdepositsenable = 0;
		option_bankdeposits:SetChecked(false);
	end
	--Mini frame open
	if (open_miniframe == nil or open_miniframe == 1) then
		open_miniframe = 1;
		GuildTitheFrame:Show();
	else
		open_miniframe = 0;
		GuildTitheFrame:Hide();
	end	
	--options open
	if (open_options == nil or open_options == 0) then
		open_options = 0;
		GuildTitheOptionsFrame:Hide();
	else
		open_options = 1;
		GuildTitheOptionsFrame:Show();
	end	
	
	--Convert all money
	ConvertToRealMoney();
    
	--Display tithe amount in mini frame
	MiniAmount:SetText("Tithe - " .. convertedtithe2);
	DEFAULT_CHAT_FRAME:AddMessage(prefix .. "Loaded. Use '/guildtithe' for options");
end

function SaveOptions()
	--Save small change self tithe option
	if(option_SCself:GetChecked() == 1) then
		option_SCselfenable = 1;
	else
		option_SCselfenable = 0;
	end
	--Save small change guild tithe option
	option_SCguildenable = 0;

    option_SmallChangeTithePercentage = SmallChange_TithePercentage:GetValue()
    option_QuestRewardsTithePercentage = QuestRewards_TithePercentage:GetValue()
    option_VendorTithePercentage = Vendor_TithePercentage:GetValue()
    option_MailBoxTithePercentage = MailBox_TithePercentage:GetValue()

	--Save quest reward self tithe option
	if(option_QRself:GetChecked() == 1) then
		option_QRselfenable = 1;
	else
		option_QRselfenable = 0;
	end
	--Quest reward guild tithe option
	option_QRguildenable = 0;

	--Save Vendor self tithe option
	if(option_VEself:GetChecked() == 1) then
		option_VEselfenable = 1;
	else
		option_VEselfenable = 0;
	end
	--Vendor guild tithe option
    option_VEguildenable = 0;

	--Save Mailbox self tithe option
	if(option_MBself:GetChecked() == 1) then
		option_MBselfenable = 1;
	else
		option_MBselfenable = 0;
	end

    option_MBguildenable = 0;

	--Save spam chat option
	if(option_spamchat:GetChecked() == 1) then
		option_spamchatenable = 1;
	else
		option_spamchatenable = 0;
	end
	--Save bank deposit option
	if(option_bankdeposits:GetChecked() == 1) then
		option_bankdepositsenable = 1;
	else
		option_bankdepositsenable = 0;
	end
end

function OutPutTitheMessage(source, source_tithe)
	--Convert to real money
	convertedtithe3 = GetCoinText(titheamountincopper, " "); --Text string without icons
	
	--Output message to chat if allowed
	if(option_spamchatenable == 1) then
		if(convertedtithe3 == "") then
			convertedtithe3 = 0;
		end
		if (titheamountincopper > 0) then
		    DEFAULT_CHAT_FRAME:AddMessage(prefix .. convertedtithe3 .. " added to Guild Tithe from " .. source.." ("..source_tithe.."%)");
		end
	end
end